﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using phpMyAdminToolkit.Common;
using System.IO;

namespace phpMyAdminToolkit.Dump
{
	public class phpMyAdminDumper
	{
		public event EventHandler<phpMyAdminActivity> Activity;

		private void OnActivity(phpMyAdminActivity phpMyAdminProgress)
		{
			if (Activity != null)
				Activity(this, phpMyAdminProgress);
		}

		public void Dump(Uri pmaUri, string user, string password, string databaseName, string backupDirectory, string sqlCommand, string includedTables, string excludedTables)
		{
			if (pmaUri == null)
				throw new ArgumentException(string.Empty, "pmaUri");

			if (string.IsNullOrEmpty(user))
				throw new ArgumentException(string.Empty, "user");

			if (string.IsNullOrEmpty(password))
				throw new ArgumentException(string.Empty, "password");

			if (string.IsNullOrEmpty(databaseName))
				throw new ArgumentException(string.Empty, "databaseName");

			if (!Directory.Exists(backupDirectory))
				throw new ArgumentException(string.Empty, "backupDirectory");

			phpMyAdminManager pma = new phpMyAdminManager();

			pma.Activity += delegate(object sender, phpMyAdminActivity e)
			{
				OnActivity(e);
			};

			// Login.
			try
			{
				pma.Login(pmaUri, user, password);
			}
			catch
			{
				throw;
			}

			// Execute command, if any.
			if (!string.IsNullOrEmpty(sqlCommand))
			{
				try
				{
					pma.ExecuteSqlCommand(sqlCommand, databaseName, null);
				}
				catch
				{
					throw;
				}
			}

			// Export.
			try
			{
				pma.ExportDatabase(databaseName, backupDirectory, includedTables, excludedTables);
			}
			catch
			{
				throw;
			}
		}
	}
}
